package com.cs.beneficios.web.action;

import com.cs.beneficios.business.entity.AreasDAO;
import com.cs.beneficios.business.entity.ProgramaDAO;
import com.cs.beneficios.business.entity.RepBeneficioOtorgadoDAO;
import com.cs.beneficios.business.entity.ReportTotalBenBerDAO;
import com.cs.beneficios.business.entity.SedeDAO;
import com.cs.beneficios.business.entity.SubProgramaDAO;
import com.cs.beneficios.business.entity.SubprogramaSedeDAO;
import com.cs.beneficios.business.model.ProgramaVO;
import com.cs.beneficios.business.model.RepDetBeneficiarioVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.paoyer.administration.business.model.UserVO;

import java.io.IOException;

import java.sql.SQLException;

import java.util.Collection;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ReportTotalBENBERAction extends Action {
	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		Object codePrograma = (Object) request.getParameter("codePrograma");
		// ConnectionFactory cf = new
		// ConnectionFactory("beneficios","beneficios");
		ConnectionFactory cf = new ConnectionFactory();
		HttpSession session = request.getSession();
		UserVO user = (UserVO) session.getAttribute("userInfo");
		session.removeAttribute("msg");
		session.setAttribute("msg", "");
		Collection areas = null;
		Collection programas = null;
		Collection subprogramas = null;
		Collection sedes = null;
		ProgramaDAO objProgramaDAO;
		SubProgramaDAO objSubProgramaDAO;
		SedeDAO objSedeDAO;
		SubprogramaSedeDAO objSubsedeDAO;
		ReportTotalBenBerDAO objDetBene;
		session.removeAttribute("Beneficios");
		String strarea = request.getParameter("codearea");

		try {
			objSedeDAO = new SedeDAO(cf);
			sedes = objSedeDAO.TotalSedes();
			cf.closeConnection(objSedeDAO.getConn());
		} catch (SQLException e) {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSUB - cwsub ********/");
		}
		if (sedes.size() > 0) {
			session.setAttribute("sedes", sedes);

			try {
				AreasDAO objAreaDAO = new AreasDAO(cf);
				areas = objAreaDAO
						.getAreasAuthorized(String.valueOf(user.getCode()),
								user.getUserGroupName());
				cf.closeConnection(objAreaDAO.getConn());
			} catch (SQLException e) {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSUB - cwsub ********/");
			}

			if (areas.size() > 0) {
				session.setAttribute("areas", areas);

				if ((Object) strarea != null && !strarea.equals("nulo")) {
					session.removeAttribute("programas");
					session.removeAttribute("subprogramas");

					try {
						objProgramaDAO = new ProgramaDAO(cf);
						ProgramaVO objProgramaVO = new ProgramaVO();
						objProgramaVO.setCodeArea(new Long(strarea));
						programas = (List) objProgramaDAO
								.findProgramaByCriterea(objProgramaVO,
										user.getUserGroupName(),
										user.getCode(), user.getCodeArea());
						cf.closeConnection(objProgramaDAO.getConn());
					} catch (SQLException e) {
						System.err.println("/******** TDSUB - cwsub");
						e.printStackTrace();
						System.err.println("TDSUB - cwsub ********/");
					}
					if (programas.size() > 0) {
						session.setAttribute("programas", programas);
					}

				} else {
					try {
						RepBeneficioOtorgadoDAO objBeneOtor1DAO = new RepBeneficioOtorgadoDAO(
								cf);
						programas = objBeneOtor1DAO.findProgramaByUserReport(
								user.getCode(), user.getUserGroupName(),
								user.getCodeArea());
						cf.closeConnection(objBeneOtor1DAO.getConn());
					} catch (SQLException e) {
						System.err.println("/******** TDSUB - cwsub");
						e.printStackTrace();
						System.err.println("TDSUB - cwsub ********/");
					}
					session.removeAttribute("msg");
					if (programas.size() > 0) {
						session.setAttribute("programas", programas);
					} else {
						session.setAttribute("msg",
								"No se encontraron programas vigentes a la fecha..");
					}
				}
				if (codePrograma != null) {

					String codpro = (String) codePrograma;
					if (!codpro.equals("nulo")) {
						try {
							RepBeneficioOtorgadoDAO objBeneOtor2DAO = new RepBeneficioOtorgadoDAO(
									cf);
							String strCodeProg = (String) codePrograma;
							subprogramas = objBeneOtor2DAO
									.findSubProgramaByUserReport(
											user.getCode(),
											user.getUserGroupName(),
											strCodeProg, user.getCodeArea());
							cf.closeConnection(objBeneOtor2DAO.getConn());
						} catch (SQLException e) {
							System.err.println("/******** TDSUB - cwsub");
							e.printStackTrace();
							System.err.println("TDSUB - cwsub ********/");
						}
						session.removeAttribute("msg");
						if (subprogramas.size() > 0) {
							session.setAttribute("subprogramas", subprogramas);
						} else {
							session.setAttribute("msg",
									"No se encontraron subprogramas asociados a este programa que esten vigentes..");
						}
					} else {
						session.setAttribute("msg", "");
						session.removeAttribute("subprogramas");
					}
				}
			} else {
				session.setAttribute("msg", "No se encontraron areas..");
			}
		} else {
			session.setAttribute("msg",
					"No se encontraron sedes vigentes a la fecha..");
		}

		Object accion = request.getParameter("acciones");
		Object codeSede = request.getParameter("code");
		Object codeSubprograma = request.getParameter("codeSubPrograma");
		Object desde = request.getParameter("desde");
		Object hasta = request.getParameter("hasta");
		Object cantidad = request.getParameter("cantidad");
		String codeSede1 = (String) codeSede;
		String codeSubprograma1 = (String) codeSubprograma;
		String codePrograma1 = (String) codePrograma;

		// fecha inicial
		Object obdia1 = (Object) request.getParameter("dia1");
		String dia1 = (String) obdia1;
		Object obmes1 = (Object) request.getParameter("mes1");
		String mes1 = (String) obmes1;
		Object obano1 = (Object) request.getParameter("ano1");
		String ano1 = (String) obano1;
		String fechaini = "";
		String fechafinal = "";
		if (obdia1 != null && obmes1 != null && obano1 != null) {
			if (!dia1.equals("nulo") && !mes1.equals("nulo")
					&& !ano1.equals("nulo")) {
				fechaini = dia1 + "/" + mes1 + "/" + ano1;
			} else {
				// System.out.println("La fecha inicial es incorrecta");
			}

		}

		// fecha final
		Object obdia2 = (Object) request.getParameter("dia2");
		String dia2 = (String) obdia2;
		Object obmes2 = (Object) request.getParameter("mes2");
		String mes2 = (String) obmes2;
		Object obano2 = (Object) request.getParameter("ano2");
		String ano2 = (String) obano2;
		boolean continuar = true;
		if (obdia2 != null && obmes2 != null && obano2 != null) {
			if (!dia2.equals("nulo") && !mes2.equals("nulo")
					&& !ano2.equals("nulo")) {
				fechafinal = dia2 + "/" + mes2 + "/" + ano2;
			} else {// validar fecha
				if (!dia2.equals("nulo") && mes2.equals("nulo")
						&& ano2.equals("nulo")) {
					request.setAttribute("errorfecha",
							"La fecha final es incorrecta");
					continuar = false;
				} else {
					if (dia2.equals("nulo") && !mes2.equals("nulo")
							&& ano2.equals("nulo")) {
						request.setAttribute("errorfecha",
								"La fecha final es incorrecta");
						continuar = false;
					} else {
						if (dia2.equals("nulo") && mes2.equals("nulo")
								&& !ano2.equals("nulo")) {
							request.setAttribute("errorfecha",
									"La fecha final es incorrecta");
							continuar = false;
						}
					}
				}// fin validar fecha

			}
		}

		if (!fechaini.equals("") && !fechafinal.equals("")) {
			String strfinicial = ano1 + mes1 + dia1;
			String strffinal = ano2 + mes2 + dia2;
			int finicial = Integer.parseInt(strfinicial.trim());
			int ffinal = Integer.parseInt(strffinal.trim());
			if (finicial > ffinal) {
				continuar = false;
				request.setAttribute("errorfecha",
						"La fecha inicial es mayor a la final");
			}
		}

		if (obdia1 != null && obmes1 != null && obano1 != null) {
			if (continuar) {
				String accion1 = (String) accion;
				session.removeAttribute("beneficiosSede");
				if (accion1.equals("BuscarTodo")) {
					Collection cobeneficio = null;
					try {

						RepDetBeneficiarioVO objDetBeneVO = new RepDetBeneficiarioVO();
						if (codeSede != null && !codeSede1.equals("nulo")) {
							objDetBeneVO
									.setCodeSede(new Long((String) codeSede));
						}
						if (codePrograma != null
								&& !codePrograma1.equals("nulo")) {
							objDetBeneVO.setCodePrograma(new Long(
									(String) codePrograma));
						}
						if (codeSubprograma != null
								&& !codeSubprograma1.equals("nulo")) {
							objDetBeneVO.setCodeSubprograma(new Long(
									(String) codeSubprograma));
						}
						if (!fechaini.equals("")) {

							objDetBeneVO.setDesde(fechaini);
						}
						if (!fechafinal.equals("")) {
							objDetBeneVO.setHasta(fechafinal);

						}
						if ((Object) strarea != null && !strarea.equals("nulo")) {
							objDetBeneVO.setCodeArea(new Long(strarea));
						}
						session.setAttribute("Parametros", objDetBeneVO);

						objDetBene = new ReportTotalBenBerDAO(cf);
						objDetBeneVO = objDetBene.getFilters(objDetBeneVO);
						cobeneficio = objDetBene
								.GetBeneficiosBeneficiarios(objDetBeneVO);
						cf.closeConnection(objDetBene.getConn());

						if (cobeneficio != null) {
							if (cobeneficio.size() > 0) {
								session.setAttribute("Beneficios", cobeneficio);
								session.setAttribute("Filters", objDetBeneVO);
							} else {
								session.removeAttribute("Beneficios");
							}
						}
						objDetBeneVO = null;
					} catch (SQLException e) {
						System.err.println("/******** TDSUB - cwsub");
						e.printStackTrace();
						System.err.println("TDSUB - cwsub ********/");
					}
				}
			}
		}
		Object obIR = request.getParameter("seleccionar");
		if (obIR == null || accion.equals("BuscarSubprogrmas")
				|| accion.equals("areas")) {
			return mapping.findForward("success");
		} else {
			return mapping.findForward("ir");
		}
	}
}